package com.lc.luzhengtang.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lc.luzhengtang.BaseApplication;
import com.lc.luzhengtang.R;
import com.lc.luzhengtang.adapter.ClassfiyGridAdapter;
import com.lc.luzhengtang.base.BaseActivity;
import com.lc.luzhengtang.bean.CommenBean;
import com.lc.luzhengtang.conn.ConnAddShop;
import com.lc.luzhengtang.conn.ConnCommodity;
import com.lc.luzhengtang.conn.ConnGoodsCommodity;
import com.lc.luzhengtang.layoutmanager.FullyGridLayoutManager;
import com.lc.luzhengtang.util.LovelyToast;
import com.zcx.helper.http.AsyCallBack;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by Administrator on 2017/5/3.
 */

public class ClassficationDetailActivity extends BaseActivity implements BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    ImageView imgNews;
    @BindView(R.id.text_price)
    TextView textPrice;
    @BindView(R.id.text_sort_order)
    TextView textSortOrder;
    @BindView(R.id.text_goods_comment)
    TextView textGoodsComment;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SwipeRefreshLayout refreshLayout;
    ClassfiyGridAdapter classfiyGridAdapter;
    String goods_id;
    public int currentPage = 1;
    public int type = 1;
    List<ConnCommodity.DataBeanX.DataBean> results;
    Drawable drawable;
    @BindView(R.id.text_title)
    TextView textTitle;
    public BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_classfication_detail);
        ButterKnife.bind(this);
        imgNews = (ImageView) findViewById(R.id.img_news);
        LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver, new IntentFilter(ShopDetailActivity.TURN_TO_CART));
        https:
//www.baidu.com/s?ie=utf-8&wd=%E6%B5%AA%E7%90%B4%E5%85%A8%E9%83%A8%E6%89%8B%E8%A1%A8&tn=98012088_4_dg&ch=14&rsv_lu=1_pn&fenlei=mv6qUZNxTZn0IZRqIHc4nHR1PHD0T1dbuW79rHIhmymvmHFbmhD30ZwV5HcvrHc4PjmsnfKWuWYk0ZFB5H00UZNopHYz0AP8IA3qP1Ilm-qWTZc0TLPs5HD0TLPsnWYk0ZwYTjYk0AwYTjYk0A-YUHYs0ZIG5Hf0uMPWpAdb5Hc0IAfqnWbkPHndnfKdThsqpZwYTaR1fiRzwBRzwMILIzRzwHFWIAt-nbNWUvY-nbuouBRzwWcsnHmsniRzwWf3P1fsPiRzwy9YUys0
        imgNews.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        if (TextUtils.isEmpty(getIntent().getStringExtra("title"))) {
            textTitle.setText("商品分类");
        } else {
            textTitle.setText(getIntent().getStringExtra("title"));
        }


        goods_id = getIntent().getStringExtra("goodstype_id");
        if (TextUtils.isEmpty(goods_id)) {
            finish();
        }
        drawable = ContextCompat.getDrawable(ClassficationDetailActivity.this, R.drawable.line_divider);
     /*  recyclerView.addItemDecoration(new SimpleDividerItemDecoration(ClassficationDetailActivity.this, drawable, 1));
        recyclerView.addItemDecoration(new GridDivider(ClassficationDetailActivity.this,2,drawable));*/
        initData();
    }


    protected void initData() {
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        //recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setLayoutManager(new FullyGridLayoutManager(ClassficationDetailActivity.this, 2));

        classfiyGridAdapter = new ClassfiyGridAdapter(null);
        classfiyGridAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
        classfiyGridAdapter.isFirstOnly(false);
        recyclerView.setAdapter(classfiyGridAdapter);
        refreshLayout.setColorSchemeColors(Color.RED, Color.BLUE, Color.GREEN);
        refreshLayout.setOnRefreshListener(this);
        classfiyGridAdapter.setOnLoadMoreListener(this);

        //开启loading,获取数据
        setRefreshing(true);
        onRefresh();
    }

    @OnClick({R.id.text_price, R.id.text_sort_order, R.id.text_goods_comment})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.text_price:
                type = 1;
                textPrice.setTextColor(getResources().getColor(R.color.classfiy_select));
                textSortOrder.setTextColor(getResources().getColor(R.color.classfiy_unselect));
                textGoodsComment.setTextColor(getResources().getColor(R.color.classfiy_unselect));
                initData();
                break;
            case R.id.text_sort_order:
                type = 2;
                textPrice.setTextColor(getResources().getColor(R.color.classfiy_unselect));
                textSortOrder.setTextColor(getResources().getColor(R.color.classfiy_select));
                textGoodsComment.setTextColor(getResources().getColor(R.color.classfiy_unselect));
                initData();
                break;
            case R.id.text_goods_comment:
                type = 3;
                textPrice.setTextColor(getResources().getColor(R.color.classfiy_unselect));
                textSortOrder.setTextColor(getResources().getColor(R.color.classfiy_unselect));
                textGoodsComment.setTextColor(getResources().getColor(R.color.classfiy_select));
                initData();
                break;
        }
    }

    @Override
    public void onRefresh() {
        new ConnGoodsCommodity(goods_id, 1, type, BaseApplication.basePreferences.readUid(), new AsyCallBack<ConnCommodity>() {

            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
                //  showLoading();
                classfiyGridAdapter.setEnableLoadMore(false);
                refreshLayout.setRefreshing(true);
                //classfiyGridAdapter.setEnableLoadMore(false);
            }

            @Override
            public void onSuccess(String toast, int type, Object o, ConnCommodity connCommodity) throws Exception {
                super.onSuccess(toast, type, o, connCommodity);
//                dataBeanList.clear();
//                dataBeanList.addAll(connCommodity.getData().getData());
//                PAGE_SIZE = connCommodity.getData().getPer_page();
                results = connCommodity.getData().getData();

                if (results != null) {
                    currentPage = 1;
                    classfiyGridAdapter.setNewData(results);
                }


                    classfiyGridAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {


                        @Override
                        public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                            String price = results.get(position).getSales();
                            new ConnAddShop(results.get(position).getId() + "", BaseApplication.basePreferences.readUid(), "1", "盒", price, new AsyCallBack<CommenBean>() {
                                @Override
                                public void onStart(int type) throws Exception {
                                    super.onStart(type);
                                }

                                @Override
                                public void onSuccess(String toast, int type, Object o, CommenBean commenBean) throws Exception {
                                    super.onSuccess(toast, type, o, commenBean);
                                    //  Toast.makeText(getActivity(), "成功加入购物车", Toast.LENGTH_SHORT).show();
                                    LovelyToast.makeText(ClassficationDetailActivity.this, "成功加入购物车", 0, LovelyToast
                                            .SUCCESS, LovelyToast.SCALE);
                                }

                                @Override
                                public void onFail(String toast, int type) throws Exception {
                                    super.onFail(toast, type);
                                }

                                @Override
                                public void onEnd(String toast, int type) throws Exception {
                                    super.onEnd(toast, type);
                                    //可能需要移除之前添加的布局
                                    classfiyGridAdapter.removeAllFooterView();
                                    //最后调用结束刷新的方法
                                    setRefreshing(false);
                                }
                            }

                            ).execute(ClassficationDetailActivity.this, false);
                        }
                    });





            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                //   dismissLoading();

            }


            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
                refreshLayout.setRefreshing(false);
                classfiyGridAdapter.setEnableLoadMore(false);
                //dismissLoading();
            }

        }).execute(ClassficationDetailActivity.this, false);


    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    public void onLoadMoreRequested() {
        new ConnGoodsCommodity(goods_id, currentPage, type, BaseApplication.basePreferences.readUid(), new AsyCallBack<ConnCommodity>() {

            @Override
            public void onStart(int type) throws Exception {
                super.onStart(type);
                //  showLoading();
                classfiyGridAdapter.setEnableLoadMore(true);
                //classfiyGridAdapter.setEnableLoadMore(false);
            }

            @Override
            public void onSuccess(String toast, int type, Object o, ConnCommodity connCommodity) throws Exception {
                super.onSuccess(toast, type, o, connCommodity);

                results = connCommodity.getData().getData();

                if (results != null && results.size() > 0) {
                    currentPage++;
                    classfiyGridAdapter.setNewData(results);
                } else {
                    //显示没有更多数据
                    // newsAdapter.loadComplete();
                    classfiyGridAdapter.loadMoreComplete();
                    View noDataView = LayoutInflater.from(ClassficationDetailActivity.this).inflate(R.layout.item_no_data, (ViewGroup) recyclerView.getParent(), false);
                    classfiyGridAdapter.addFooterView(noDataView);
                }


                classfiyGridAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                    @Override
                    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                        new ConnAddShop(results.get(position).getId() + "", BaseApplication.basePreferences.readUid(), "1", "1", "1", new AsyCallBack<CommenBean>() {
                            @Override
                            public void onStart(int type) throws Exception {
                                super.onStart(type);
                            }

                            @Override
                            public void onSuccess(String toast, int type, Object o, CommenBean commenBean) throws Exception {
                                super.onSuccess(toast, type, o, commenBean);
                                //  Toast.makeText(getActivity(), "成功加入购物车", Toast.LENGTH_SHORT).show();
                                LovelyToast.makeText(ClassficationDetailActivity.this, "成功加入购物车", 0, LovelyToast
                                        .SUCCESS, LovelyToast.SCALE);
                            }

                            @Override
                            public void onFail(String toast, int type) throws Exception {
                                super.onFail(toast, type);
                            }

                            @Override
                            public void onEnd(String toast, int type) throws Exception {
                                super.onEnd(toast, type);
                                //可能需要移除之前添加的布局
                                classfiyGridAdapter.removeAllFooterView();
                                //最后调用结束刷新的方法
                                setRefreshing(false);
                            }
                        }

                        ).execute(ClassficationDetailActivity.this, false);
                    }
                });


            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                //   dismissLoading();

            }


            @Override
            public void onEnd(String toast, int type) throws Exception {
                super.onEnd(toast, type);
                refreshLayout.setRefreshing(false);
                //dismissLoading();
                classfiyGridAdapter.removeAllFooterView();
                //最后调用结束刷新的方法
                setRefreshing(false);
            }

        }).execute(ClassficationDetailActivity.this, false);
    }

    public void setRefreshing(final boolean refreshing) {
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(refreshing);
            }
        });
    }

}
